import { isNum } from "@/utils/validate";
/**
 * 验证金额小数位不能超过6位，只能精确到分
 * @param {string} str
 * @returns
 */
export function isMoney(str) {
    const reg =  /^(-?)(\d*(\.\d{0,6})?)$/;
    return reg.test(str);
  }
  
  //JS 精确计算 减法   
  export function FloatSub(arg1,arg2){  
    if (!arg1 || !isNum(arg1)) {
        arg1 = 0.0;
    }
    if (!arg2 || !isNum(arg2)) {
        arg2 = 0.0;
    }
    var r1,r2,m,n;   
    try{r1=arg1.toString().split(".")[1].length;}catch(e){r1=0;}   
    try{r2=arg2.toString().split(".")[1].length;}catch(e){r2=0;}   
    m=Math.pow(10,Math.max(r1,r2));   
    //动态控制精度长度   
    n=(r1>=r2)?r1:r2;   
    return parseFloat(((arg1*m-arg2*m)/m).toFixed(n));   
  }
  //JS 精确计算 加法
  export function FloatAdd(arg1,arg2){   
    if (!arg1 || !isNum(arg1)) {
        arg1 = 0.0;
    }
    if (!arg2 || !isNum(arg2)) {
        arg2 = 0.0;
    }
    var r1,r2,m,n;   
    try{r1=arg1.toString().split(".")[1].length;}catch(e){r1=0;}   
    try{r2=arg2.toString().split(".")[1].length;}catch(e){r2=0;}  
    m=Math.pow(10,Math.max(r1,r2));
    //动态控制精度长度   
    n=(r1>=r2)?r1:r2; 
    return parseFloat(((arg1*m+arg2*m)/m).toFixed(n));   
  } 

 //JS 精确计算 乘法
 export function FloatMul(arg1,arg2){   
    if (!arg1 || !isNum(arg1)) {
        arg1 = 0.0;
    }
    if (!arg2 || !isNum(arg2)) {
        arg2 = 0.0;
    }
    var m=0,s1=arg1.toString(),s2=arg2.toString();    
    try{m+=s1.split(".")[1].length;}catch(e){}    
    try{m+=s2.split(".")[1].length;}catch(e){}   
    var result = Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
    return isNaN(result) ? 0 : result;   
  }

export function isNum1(str) {
  const reg = /^-?\d+(\.\d+)?$/;
  return reg.test(str);
}

  //JS 精确计算 除法
  export function FloatDiv(arg1,arg2){ 
    if (!arg1 || !isNum1(arg1)) {
        arg1 = 0.0;
    }
    if (!arg2 || !isNum(arg2)) {
        arg2 = 0.0;
    }
    var t1=0,t2=0,r1,r2;    
    try{t1=arg1.toString().split(".")[1].length;}catch(e){}    
    try{t2=arg2.toString().split(".")[1].length;}catch(e){}  
    // r1=Number(arg1.toString().replace(".",""));    
    // r2=Number(arg2.toString().replace(".",""));
    // var result = (r1/r2)*Math.pow(10,t2-t1);
    // return isNaN(result) ? 0 : result;          
    var step = Math.pow(10, Math.max(t1, t2));
    var  result = (arg1 * step) / (arg2 * step);
    return transferToNumber(result);      
  }

  // 处理出现科学计数法
function transferToNumber(num) {
    if (isNaN(num)) {
      return num
    }
    num = '' + num
    num = parseFloat(num)
    let eformat = num.toExponential() // 转换为标准的科学计数法形式（字符串）
    let tmpArray = eformat.match(/\d(?:\.(\d*))?e([+-]\d+)/) // 分离出小数值和指数值
    let number = num.toFixed(Math.max(0, (tmpArray[1] || '').length - tmpArray[2]))
    return number 
}